<template>
    <!-- 修改承运合同页面 -->
    <div class="page">
        <h2 class="page-title">修改承运合同</h2>

        <!-- 表单区域 -->
        <div class="form-grid">
            <!-- 合同编号 - 只读显示 -->
            <div class="form-item">
                <label>合同编号:</label>
                <input v-model="form.contractNumber" readonly placeholder="合同编号" style="background-color: #f5f5f5;" />
            </div>

            <!-- 合同标题 - 必填项 -->
            <div class="form-item required">
                <label>合同标题:</label>
                <input v-model="form.contractTitle" placeholder="请输入合同标题" />
            </div>

            <!-- 承运单位选择 - 必填项，支持二级联动 -->
            <div class="form-item required">
                <label>承运单位:</label>
                <select v-model.number="form.unitId" @change="onUnitChange">
                    <option value="" disabled>请选择承运单位</option>
                    <option v-for="u in unitOptions" :key="u.id" :value="u.id">{{ u.name }}</option>
                </select>
            </div>

            <!-- 承运负责人选择 - 根据承运单位联动显示 -->
            <div class="form-item">
                <label>承运负责人:</label>
                <select v-model="form.carriageRepresentative">
                    <option value="" disabled>请选择承运负责人</option>
                    <option v-for="o in ownerOptions" :key="o" :value="o">{{ o }}</option>
                </select>
            </div>

            <!-- 线路（文本框） - 改为文本输入，兼容手动填写线路名或 ID -->
            <div class="form-item">
                <label>线 路:</label>
                <input v-model="form.route_infoId" placeholder="请输入线路" />
            </div>

            <!-- 吨运价 - 数字输入 -->
            <div class="form-item">
                <label>吨 运 价:</label>
                <input v-model.number="form.tonFreightRate" placeholder="请输入吨运价" type="number" step="0.01" />
            </div>

            <!-- 包车条件吨位 - 数字输入 -->
            <div class="form-item">
                <label>包车条件吨位:</label>
                <input v-model.number="form.charterConditionTonnage" placeholder="请输入包车条件吨位" type="number"
                    step="0.01" />
            </div>

            <!-- 包车金额 - 数字输入 -->
            <div class="form-item">
                <label>包车金额:</label>
                <input v-model.number="form.charterAmount" placeholder="请输入包车金额" type="number" step="0.01" />
            </div>

            <!-- 经办人 - 自动填充当前登录用户 -->
            <div class="form-item">
                <label>经 办 人:</label>
                <input v-model="form.handler" placeholder="当前登录人" />
            </div>

            <!-- 签订时间 - 日期选择器 -->
            <div class="form-item">
                <label>签订时间:</label>
                <input type="date" v-model="signingDateStr" />
            </div>

            <!-- 合同金额 - 数字输入 -->
            <div class="form-item">
                <label>合同金额:</label>
                <input v-model.number="form.contractAmount" placeholder="请输入合同金额" type="number" step="0.01" />
            </div>
        </div>

        <!-- 合同标的或项目说明 - 多行文本输入 -->
        <div class="form-block">
            <label>合同标的或项目说明:</label>
            <textarea v-model="form.contractSubjectDescription" rows="4" placeholder="请输入内容" />
        </div>

        <!-- 合同主要条款/变更条款 - 多行文本输入 -->
        <div class="form-block">
            <label>合同主要条款/变更条款:</label>
            <textarea v-model="form.contractTerms" rows="6" placeholder="请输入内容" />
        </div>

        <!-- 合同文本附件上传 -->
        <div class="form-block">
            <label>合同文本（附件）:</label>
            <div class="file-row">
                <input ref="fileInputRef" type="file" @change="onFileChange" />
                <span class="hint">(单个附件最大支持20M，支持: PDF、Word、Excel、Txt格式)</span>
            </div>
            <div v-if="attachmentName" class="file-name">已选择: {{ attachmentName }}</div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="btn-row">
            <button class="btn primary" :disabled="submitting" @click="submit">保存修改</button>
            <button class="btn" @click="closeDetail">关闭</button>
        </div>
    </div>
</template>

<script setup lang="ts">
// 导入Vue相关依赖
import { reactive, ref, computed, onMounted } from 'vue'
import { uploadFile } from '@/utils/fileUpload'
import { useRoute, useRouter } from 'vue-router'
import { read, write } from '@/assets/Axios/axiosHttple'

// 路由实例
const route = useRoute()
const router = useRouter()

// 下拉选项类型定义
type Option = { id: number; name: string; normalized?: string }

// 表单数据模型
const form = reactive({
    id: 0,                              // 合同ID
    contractNumber: '',                 // 合同编号
    contractTitle: '',                  // 合同标题
    unitId: 0,                          // 承运单位ID
    carriageRepresentative: '',         // 承运负责人
    route_infoId: 0,                    // 线路ID
    tonFreightRate: 0,                  // 吨运价
    charterConditionTonnage: 0,         // 包车条件吨位
    charterAmount: 0,                   // 包车金额
    signingDate: '',                    // 签订时间
    handler: '',                        // 经办人
    contractAmount: 0,                  // 合同金额
    contractSubjectDescription: '',     // 合同标的或项目说明
    contractTerms: '',                  // 合同主要条款/变更条款
    contractAttachment: ''              // 合同附件
})

// 响应式数据
const unitOptions = ref<Option[]>([])          // 承运单位选项
const ownerOptions = ref<string[]>([])         // 承运负责人选项
const routeOptions = ref<Option[]>([])         // 线路选项

// 文件上传相关
const fileInputRef = ref<HTMLInputElement | null>(null)  // 文件输入引用
const attachmentName = ref('')                           // 附件名称
const submitting = ref(false)                            // 提交状态
const uploadingFile = ref(false)

// 签订时间计算属性 - 用于日期输入框的双向绑定
const signingDateStr = computed({
    get() {
        // 将ISO日期字符串转换为YYYY-MM-DD格式
        if (!form.signingDate) return ''
        const d = new Date(form.signingDate)
        if (Number.isNaN(d.getTime())) return ''
        const y = d.getFullYear()
        const m = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        return `${y}-${m}-${day}`
    },
    set(v: string) {
        // 将YYYY-MM-DD格式转换为ISO日期字符串
        form.signingDate = v ? new Date(v).toISOString() : ''
    }
})

// 组件挂载时的初始化操作
onMounted(async () => {
    // 设置经办人为当前登录用户
    form.handler = localStorage.getItem('username') || '张三'

    // 获取合同ID并加载详情
    const idParam = route.query.id || route.params.id
    const id = Number(idParam)
    if (Number.isFinite(id) && id > 0) {
        form.id = id
        // 并行加载详情数据和下拉选项
        await Promise.all([
            loadDetail(id),
            loadUnits(),
            loadRoutes()
        ])
    }
})

/**
 * 加载承运合同详情
 * 从后端API获取合同详情数据并填充表单
 * @param id 合同ID
 */
async function loadDetail(id: number) {
    try {
        const base = 'contractmanagementread/api/ContractManagementControllers/GetCarriageById/Carriage'
        const tries = [
            `${base}/${encodeURIComponent(String(id))}`,
            `${base}`
        ]
        let detail: any = null
        for (const u of tries) {
            try {
                const res = u.endsWith('Carriage') ? await read.get(u, { params: { id } }) : await read.get(u)
                const j: any = res?.data ?? {}
                const code = Number(j?.code ?? j?.Code ?? (res?.status === 200 ? 200 : 500))
                if (code !== 200) continue
                const d = j?.data ?? j
                if (d && (d.Id || d.id)) { detail = d; break }
            } catch { }
        }

        if (!detail) {
            alert('加载合同详情失败')
            return
        }

        // 填充表单数据
        form.contractNumber = detail.ContractNumber ?? detail.contractNumber ?? ''
        form.contractTitle = detail.ContractTitle ?? detail.contractTitle ?? ''
        form.unitId = Number(detail.UnitId ?? detail.unitId ?? 0)
        form.carriageRepresentative = detail.PartnerContact ?? detail.CarrierContact ?? detail.carriageRepresentative ?? detail.CarriageRepresentative ?? ''
        // 如果 detail 中已包含负责人名称，确保下拉有该项以显示当前值
        if (form.carriageRepresentative) {
            ownerOptions.value = ownerOptions.value && ownerOptions.value.length > 0 ? ownerOptions.value : [String(form.carriageRepresentative)]
        }
        form.route_infoId = Number(detail.RouteId ?? detail.route_infoId ?? 0)
        form.tonFreightRate = Number(detail.TonFreightRate ?? detail.tonFreightRate ?? 0)
        form.charterConditionTonnage = Number(detail.CharterConditionTonnage ?? detail.charterConditionTonnage ?? 0)
        form.charterAmount = Number(detail.CharterAmount ?? detail.charterAmount ?? 0)
        form.contractAmount = Number(detail.ContractAmount ?? detail.contractAmount ?? 0)
        form.contractSubjectDescription = detail.ContractSubjectDescription ?? detail.contractSubjectDescription ?? ''
        form.contractTerms = detail.ContractTerms ?? detail.contractTerms ?? ''

        // 处理签订时间
        const signing = detail.SigningDate ?? detail.signingDate
        form.signingDate = signing ? new Date(signing).toISOString() : ''

        // 如果已有承运单位ID，加载对应的承运负责人
        if (form.unitId) {
            await fetchCargoOwnerByUnitId(form.unitId)
        }

    } catch (e) {
        alert('加载合同详情失败')
    }
}

/**
 * 加载承运单位数据
 * 从外部合作单位API获取数据，填充承运单位下拉框
 */
async function loadUnits() {
    try {
        const res = await read.get('baseinforead/api/External/GetExternalList', { params: { PageIndex: 1, PageSize: 999 } })
        const j: any = res?.data ?? {}
        const dataBlock = j?.data || j
        const list = Array.isArray(dataBlock) ? dataBlock : (Array.isArray(dataBlock?.data) ? dataBlock.data : [])

        // 映射数据格式，支持多种字段名
        unitOptions.value = list.map((x: any) => {
            const name = x.UnitName ?? x.unitName ?? x.Name ?? x.name ?? x.CompanyName ?? x.companyName ?? ''
            const normalized = String(name || '').replace(/\s+/g, '').replace(/[\-_,.·•()（）]/g, '').toLowerCase()
            return { id: Number(x.Id ?? x.id ?? x.UnitId ?? x.unitId), name, normalized }
        }).filter((x: any) => Number.isFinite(x.id) && x.name)
    } catch (error) {
        // 静默处理错误
    }
}

/**
 * 承运单位变化处理函数
 * 实现二级联动：选择承运单位后自动填充承运负责人
 */
async function onUnitChange() {
    if (form.unitId && Number.isFinite(form.unitId)) {
        // 根据选择的承运单位ID，查找对应的货主信息
        await fetchCargoOwnerByUnitId(Number(form.unitId))
    } else {
        // 清空承运负责人
        ownerOptions.value = []
        form.carriageRepresentative = ''
    }
}

/**
 * 根据承运单位ID获取货主信息
 * 实现二级联动：通过承运单位ID查找对应的货主信息，填充承运负责人选项
 * @param unitId 承运单位ID
 */
async function fetchCargoOwnerByUnitId(unitId: number) {
    // 同 Add 页面：宽松匹配、按名称回退、调试日志
    try {
        const res = await read.get('baseinforead/api/CargoOwner/GetCargoOwnerList', { params: { PageIndex: 1, PageSize: 999 } })
        const j: any = res?.data ?? {}
        const dataBlock = j?.data || j
        const list = Array.isArray(dataBlock) ? dataBlock : (Array.isArray(dataBlock?.data) ? dataBlock.data : [])

        const toNumber = (v: any) => { const n = Number(v); return Number.isFinite(n) ? n : NaN }

        let matchedCargoOwners = list.filter((item: any) => {
            const itemUnitId = toNumber(item.UnitId ?? item.unitId ?? item.Id ?? item.id)
            return !Number.isNaN(itemUnitId) && itemUnitId === unitId
        })

        // 如果按 id 没有匹配，尝试按单位名称回退匹配（使用 normalized 字段，忽略空格与特殊符号）
        if (matchedCargoOwners.length === 0) {
            const selectedUnit = unitOptions.value.find(u => u.id === unitId)
            const unitNormalized = selectedUnit?.normalized || selectedUnit?.name?.replace(/\s+/g, '').replace(/[\-_,.·•()（）]/g, '').toLowerCase()
            if (unitNormalized) {
                matchedCargoOwners = list.filter((item: any) => {
                    const names = [item.UnitName, item.unitName, item.CompanyName, item.companyName, item.Name, item.name]
                    return names.some((n: any) => typeof n === 'string' && n.replace(/\s+/g, '').replace(/[\-_,.·•()（）]/g, '').toLowerCase().includes(unitNormalized))
                })
            }
        }

        console.debug('[fetchCargoOwnerByUnitId] unitId=', unitId, 'matchedCount=', matchedCargoOwners.length)

        if (matchedCargoOwners.length > 0) {
            const ownerNames = matchedCargoOwners.map((item: any) => {
                return item.ownerName ?? item.OwnerName ?? item.Contact ?? item.contact ?? item.Principal ?? item.principal ?? item.Name ?? item.name
            }).filter(Boolean) as string[]

            if (ownerNames.length > 0) {
                ownerOptions.value = [...new Set(ownerNames)]
                if (ownerOptions.value.length === 1) form.carriageRepresentative = ownerOptions.value[0]
                else form.carriageRepresentative = ''
            } else {
                ownerOptions.value = []
                form.carriageRepresentative = ''
            }
        } else {
            ownerOptions.value = []
            form.carriageRepresentative = ''
        }
    } catch (error) {
        console.error('[fetchCargoOwnerByUnitId] error', error)
        ownerOptions.value = []
        form.carriageRepresentative = ''
    }
}

/**
 * 加载线路数据
 * 使用5000端口的线路API获取线路信息，显示为"起始点到终点"格式
 */
async function loadRoutes() {
    // 只使用5000端口的API，因为承运合同相关页面都使用这个端口
    try {
        const res = await read.get('contractmanagementread/api/ContractManagementControllers/Route', { params: { PageIndex: 1, PageSize: 999, t: Date.now() } })
        const j: any = res?.data ?? {}
        const routeData = j?.data || {}
        const list = Array.isArray(routeData.data) ? routeData.data : (Array.isArray(j?.data) ? j.data : [])

        if (Array.isArray(list) && list.length > 0) {
            // 处理线路数据，显示为"起始点到终点"格式
            routeOptions.value = list.map((r: any) => {
                const id = Number(r.Id ?? r.id)
                const startingPoint = r.Starting_point ?? r.starting_point ?? r.StartingPoint ?? r.startingPoint ?? r.StartPoint ?? r.startPoint ?? r.From ?? r.from ?? ''
                const destination = r.Destination ?? r.destination ?? r.EndPoint ?? r.endPoint ?? r.To ?? r.to ?? ''
                const routeName = r.RouteName ?? r.routeName ?? r.Name ?? r.name ?? ''

                // 优先使用"起始点到终点"格式，如果没有则使用原有名称，并包含ID信息
                let displayName = ''
                if (startingPoint && destination) {
                    displayName = `[${id}] ${startingPoint}到${destination}`
                } else if (routeName) {
                    displayName = `[${id}] ${routeName}`
                } else {
                    displayName = `[${id}] 线路${id}`
                }

                return { id, name: displayName }
            }).filter((x: Option) => Number.isFinite(x.id) && x.name)
        }
    } catch (error) {
        // 静默处理错误
    }
}

/**
 * 线路选择变化处理函数
 * 当用户选择线路时触发
 */
function onRouteChange() {
    // 线路选择变化时的处理逻辑
}

/**
 * 文件选择变化处理函数
 * 处理合同附件上传，将文件转换为Base64格式
 * @param e 文件输入事件
 */
async function onFileChange(e: Event) {
    const input = e.target as HTMLInputElement
    const file = input.files && input.files[0]
    if (!file) return
    attachmentName.value = file.name
    uploadingFile.value = true
    try {
        try {
            const url = await uploadFile(file)
            if (url) form.contractAttachment = url
            else form.contractAttachment = file.name
        } catch (err: any) {
            console.warn('上传失败，使用文件名占位', err)
            form.contractAttachment = file.name
        }
    } finally {
        uploadingFile.value = false
        if (fileInputRef.value) fileInputRef.value.value = ''
    }
}

/**
 * 表单验证函数
 * 验证必填字段是否已填写
 * @returns 验证是否通过
 */
function validate(): boolean {
    if (!form.contractTitle) { alert('请填写合同标题'); return false }
    if (!form.unitId) { alert('请选择承运单位'); return false }
    // 线路字段已设置为可选项，不再进行必填验证
    return true
}

/**
 * 提交表单函数
 * 处理合同修改提交
 */
async function submit() {
    if (!validate()) return
    submitting.value = true
    try {
        const selectedUnit = unitOptions.value.find(u => u.id === form.unitId)
        const unitName = selectedUnit?.name || ''

        const payload = {
            id: form.id,
            contractNumber: form.contractNumber || '',
            contractTitle: form.contractTitle,
            unitId: form.unitId || 0,
            unitName: unitName,
            carriageRepresentative: form.carriageRepresentative || '',
            route_infoId: form.route_infoId || 0,
            tonFreightRate: form.tonFreightRate || 0,
            charterConditionTonnage: form.charterConditionTonnage || 0,
            charterAmount: form.charterAmount || 0,
            signingDate: form.signingDate || new Date().toISOString(),
            handler: form.handler || '张三',
            contractAmount: form.contractAmount || 0,
            contractSubjectDescription: form.contractSubjectDescription || '',
            contractTerms: form.contractTerms || '',
            contractAttachment: form.contractAttachment || '',
            lastModifiedBy: localStorage.getItem('username') || '张三'
        }

        const candidates = [
            'contractmanagementwrite/api/ContractManagement/UpdateCarriage/carriage/update',
            `contractmanagementwrite/api/ContractManagement/UpdateCarriage/carriage/update/${encodeURIComponent(String(form.id))}`,
            'contractmanagementwrite/api/ContractManagement/Update/update'
        ]
        let lastErr: any = null
        for (const u of candidates) {
            try {
                const res = await write.post(u, payload)
                const d = res?.data ?? {}
                if (res.status === 200 && (Number(d?.code) === 200 || d?.data === true || typeof d?.data === 'number')) {
                    alert('修改成功')
                    router.push('/GetCarriageContracts?refresh=1')
                    return
                }
                lastErr = { status: res?.status, body: d }
            } catch (e) { lastErr = e }
        }
        alert(lastErr?.body?.message || lastErr?.message || '修改失败')
    } catch (error: any) {
        alert(error?.message || '网络异常，请重试')
    } finally {
        submitting.value = false
    }
}

/**
 * 关闭详情函数
 * 返回承运合同列表页面
 */
function closeDetail() {
    router.push('/GetCarriageContracts')
}
</script>

<style scoped>
.page {
    padding: 16px;
}

.page-title {
    font-size: 18px;
    margin: 8px 0 16px;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px 24px;
}

.form-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.form-item>label {
    width: 110px;
    text-align: right;
    color: #333;
}

.form-item.required>label::before {
    content: '*';
    color: #f33;
    margin-right: 4px;
}

.form-item input,
.form-item select {
    flex: 1;
    height: 32px;
    padding: 4px 8px;
}

.form-block {
    margin-top: 12px;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-block textarea {
    width: 100%;
    padding: 8px;
}

.file-row {
    display: flex;
    align-items: center;
    gap: 12px;
}

.hint {
    color: #888;
    font-size: 12px;
}

.file-name {
    margin-top: 6px;
    color: #555;
}

.btn-row {
    margin-top: 20px;
    display: flex;
    gap: 12px;
}

.btn {
    height: 32px;
    padding: 0 14px;
    border: 1px solid #3b82f6;
    color: #3b82f6;
    background: #fff;
    cursor: pointer;
}

.btn.primary {
    background: #3b82f6;
    color: #fff;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
</style>